package com.jeecg.filter;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeecg.bean.vo.MVCVO;
import com.jeecg.util.AnnotiontionUtil;

public class PreActionByAnnotationMvc extends HttpServlet {

	/**
	 * mvc核心类
	 * 接受请求，然后利用反射new出请求的action.调用其方法
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String servletPath=request.getServletPath();
		String sp=servletPath.split("\\.")[0];
		 Map<String,MVCVO> map=AnnotiontionUtil.getMVCMap();
		 MVCVO vo=(MVCVO)map.get(sp);
		 Class<?> clazz=null;
		 try {
			clazz=Class.forName(vo.getClassType().getName());
			Object action=clazz.newInstance();//获取action对象实例
			Method method=clazz.getMethod(vo.getMethodName(), vo.getParamsClass());
			//获取参数值
			List<Object> paramValuesList=new ArrayList<Object>();
			List<String> paramNames=vo.getParamsName();
			for(String paramName:paramNames){
				Object paramv=request.getParameter(paramName);
				paramValuesList.add(paramv);
			}
			//调用方法
			String result=(String)method.invoke(action, paramValuesList.toArray());
			//跳转
			RequestDispatcher dis=request.getRequestDispatcher(result);
			dis.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
	}
	

}
